package com.zto.wk.webflux.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * Created by wangkuan at 2018-08-24 8:34
 */
public class Producer {
    private static Logger log = LoggerFactory.getLogger(Producer.class);

    private static final String BROKER_LIST = "test.server:9092";
    private static final KafkaProducer<String, String> producer;

    /*
    初始化生产者
     */
    static {
        Properties configs = initConfig();
        producer = new KafkaProducer<>(configs);
    }

    /*
    初始化配置
     */
    private static Properties initConfig() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return properties;
    }

    public static void main(String[] args) {
        String topic = "test_1";

        for (int i = 0; i < 10; i++) {
            send(topic, "value" + i);
        }
        producer.close();
    }

    private static void send(String topic, String content) {
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, content);

        producer.send(record, (recordMetadata, e) -> {
            if (null != e) {
                log.info("send error " + e.getMessage());
            } else {
                System.out.println(String.format("offset:%s,partition:%s", recordMetadata.offset(), recordMetadata.partition()));
            }
        });
    }

}
